package com.thunder.ktv.scoreengine2test;

import android.content.Context;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;

import java.io.IOException;
import java.util.Locale;
import java.util.concurrent.TimeUnit;

/**
 * 视频播放器封装类
 * 提供视频播放、暂停、切换音轨、音量调节等功能
 */
public class VideoPlayer implements SurfaceHolder.Callback {
    private Context context;
    private SurfaceView surfaceView;
    private SeekBar seekBarProgress;
    private SeekBar seekBarVolume;
    private TextView tvCurrentTime;
    private TextView tvTotalTime;
    private AudioManager audioManager;
    
    private MediaPlayer mediaPlayer;
    private boolean isOriginalTrack = true;
    private String videoPath;

    private Handler handler;
    private Runnable updateProgressRunnable;
    
    // 音轨索引
    private static final int TRACK_ORIGINAL = 1;  // 原唱音轨
    private static final int TRACK_ACCOMPANIMENT = 2;  // 伴唱音轨
    
    /**
     * 构造函数
     */
    public VideoPlayer(Context context, SurfaceView surfaceView, SeekBar seekBarProgress, SeekBar seekBarVolume,
                      TextView tvCurrentTime, TextView tvTotalTime) {
        this.context = context;
        this.surfaceView = surfaceView;
        this.seekBarProgress = seekBarProgress;
        this.seekBarVolume = seekBarVolume;
        this.tvCurrentTime = tvCurrentTime;
        this.tvTotalTime = tvTotalTime;
        
        this.audioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
        
        // 初始化Handler
        handler = new Handler(Looper.getMainLooper());
        
        // 设置SurfaceHolder回调
        if(surfaceView != null)
            surfaceView.getHolder().addCallback(this);
        
        initControls();
    }
    
    /**
     * 初始化控制器
     */
    private void initControls() {
        // 设置进度条监听
        seekBarProgress.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser && mediaPlayer != null) {
                    int duration = mediaPlayer.getDuration();
                    int position = (duration * progress) / 100;
                    mediaPlayer.seekTo(position);
                    updateCurrentTime(position);
                }
            }
            
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {
                // 暂停进度更新
                handler.removeCallbacks(updateProgressRunnable);
            }
            
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {
                // 恢复进度更新
                if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                    startProgressUpdate();
                }
            }
        });
        
        // 设置音量条监听
        seekBarVolume.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
                if (fromUser) {
                    int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
                    int volume = (maxVolume * progress) / 100;
                    audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, volume, 0);
                }
            }
            
            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {}
            
            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {}
        });
    }
    
    /**
     * 设置视频路径
     */
    public void setVideoPath(String path) {
        this.videoPath = path;
    }
    
    /**
     * 准备MediaPlayer
     */
    private void prepareMediaPlayer() {
        try {
            if (mediaPlayer != null) {
                mediaPlayer.release();
            }
            
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setDataSource(context, Uri.parse(videoPath));
            if(surfaceView != null)
                mediaPlayer.setDisplay(surfaceView.getHolder());
            
            // 设置音频流类型
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            
            // 设置准备完成监听
            mediaPlayer.setOnPreparedListener(mp -> {
                seekBarProgress.setMax(100);
                updateTotalTime(mediaPlayer.getDuration());
            });
            
            // 设置播放完成监听
            mediaPlayer.setOnCompletionListener(mp -> {
                stopProgressUpdate();
            });
            
            // 设置错误监听
            mediaPlayer.setOnErrorListener((mp, what, extra) -> {
                Toast.makeText(context, "播放错误: " + what, Toast.LENGTH_SHORT).show();
                return false;
            });
            
            // 准备播放器
            mediaPlayer.prepareAsync();
            
        } catch (IOException e) {
            e.printStackTrace();
            Toast.makeText(context, "准备播放器失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
        }
    }
    
    /**
     * 开始更新进度
     */
    private void startProgressUpdate() {
        if (updateProgressRunnable == null) {
            updateProgressRunnable = new Runnable() {
                @Override
                public void run() {
                    if (mediaPlayer != null && mediaPlayer.isPlaying()) {
                        int currentPosition = mediaPlayer.getCurrentPosition();
                        int duration = mediaPlayer.getDuration();
                        int progress = (duration > 0) ? (currentPosition * 100) / duration : 0;
                        seekBarProgress.setProgress(progress);
                        updateCurrentTime(currentPosition);
                        handler.postDelayed(this, 1000);
                    }
                }
            };
        }
        handler.post(updateProgressRunnable);
    }
    
    /**
     * 停止更新进度
     */
    private void stopProgressUpdate() {
        handler.removeCallbacks(updateProgressRunnable);
    }
    
    /**
     * 更新当前播放时间
     */
    private void updateCurrentTime(int milliseconds) {
        String time = formatTime(milliseconds);
        tvCurrentTime.setText(time);
    }
    
    /**
     * 更新总时长
     */
    private void updateTotalTime(int milliseconds) {
        String time = formatTime(milliseconds);
        tvTotalTime.setText(time);
    }
    
    /**
     * 格式化时间
     */
    private String formatTime(int milliseconds) {
        long minutes = TimeUnit.MILLISECONDS.toMinutes(milliseconds);
        long seconds = TimeUnit.MILLISECONDS.toSeconds(milliseconds) % 60;
        return String.format(Locale.getDefault(), "%02d:%02d", minutes, seconds);
    }
    
    /**
     * 选择音频轨道
     */
    private void selectAudioTrack(int trackIndex) {
        if (mediaPlayer != null) {
            try {
                MediaPlayer.TrackInfo[] trackInfos = mediaPlayer.getTrackInfo();
                if (trackInfos != null && trackIndex < trackInfos.length) {
                    mediaPlayer.selectTrack(trackIndex);
                }
            } catch (Exception e) {
                e.printStackTrace();
                Toast.makeText(context, "切换音轨失败: " + e.getMessage(), Toast.LENGTH_SHORT).show();
            }
        }
    }
    
    /**
     * 开始播放
     */
    public void start() {
        if (mediaPlayer != null && !mediaPlayer.isPlaying()) {
            mediaPlayer.start();
            startProgressUpdate();
        }
    }
    
    /**
     * 暂停播放
     */
    public void pause() {
        if (mediaPlayer != null && mediaPlayer.isPlaying()) {
            mediaPlayer.pause();
            stopProgressUpdate();
        }
    }

    public long getCurrentPosition() {
        if(mediaPlayer != null){
            try {
                return mediaPlayer.getCurrentPosition();
            }catch (Exception ew){
                return -1;
            }
        }
        return 0;
    }
    
    /**
     * 切换音轨
     */
    public void switchTrack() {
        isOriginalTrack = !isOriginalTrack;
        int trackIndex = isOriginalTrack ? TRACK_ORIGINAL : TRACK_ACCOMPANIMENT;
        selectAudioTrack(trackIndex);
    }
    
    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (videoPath != null) {
            prepareMediaPlayer();
        }
    }
    
    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
        // 不需要处理
    }
    
    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        if (mediaPlayer != null) {
            stopProgressUpdate();
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }
    
    /**
     * 释放资源
     */
    public void release() {
        stopProgressUpdate();
        if (mediaPlayer != null) {
            mediaPlayer.release();
            mediaPlayer = null;
        }
    }
    
    /**
     * 是否正在播放
     */
    public boolean isPlaying() {
        return mediaPlayer != null && mediaPlayer.isPlaying();
    }
} 